/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.uct.controller  
 */
package com.apache.uct.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.apache.api.manager.BaseManager;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.api.vo.Token;
import com.apache.database.constant.SystemTools;
import com.apache.database.constant.Validator;
import com.apache.database.model.Page;
import com.apache.tools.DateUtils;
import com.apache.uct.common.BaseAction;
import com.apache.uct.common.entity.Act;
import com.apache.uct.common.entity.ActGive;
import com.apache.uct.common.entity.Org;
import com.apache.uct.common.entity.Role;
import com.apache.uct.common.entity.User;
import com.apache.uct.manager.ActGiveManager;
import com.apache.uct.manager.OrgManager;
import com.apache.uct.manager.RoleManager;

/**
 * description:  角色管理action
 * @author dwusoft 创建时间：2015-3-23  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
@Controller
@RequestMapping("uct/role/")
public class RoleAction extends BaseAction<Role> {

	@Autowired
	private RoleManager roleManager;
	@Autowired
	private ProxyManager uctProxyManager;
	@Autowired
	private ActGiveManager actGiveManager;
	@Autowired
	private OrgManager orgManager;

	/**
	 * 功能说明：跳转到列表查询页面
	 */
	@RequestMapping("list.action")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView view = new ModelAndView(LIST);
		String orgId = request.getParameter("orgId");
		if (Validator.isNotNull(orgId)) {
			request.setAttribute("orgId", orgId);
		}
		return view;
	}

	@RequestMapping("role!data.action")
	@ResponseBody
	protected Object data(HttpServletRequest request, String page, String rows) {
		ParamsVo<Role> vo = new ParamsVo<Role>();
		Role role = new Role();
		User user = this.getSessionUser(request);
		if ("1".equals(SystemTools.getInstance().getValue("org_act_switch"))) {
			vo.setParams("orgId", user.getOrgId());
			vo.setParams("sysUser", this.getSysFlag(request));
		} else {
			String orgId = request.getParameter("orgId");
			if (Validator.isNotNull(orgId)) {
				role.setDelStatus(orgId);
				request.setAttribute("orgId", orgId);
			}
		}
		vo.setParams("pageIndex", page);
		vo.setParams("pageSize", rows);
		vo.setObj(role);
		Page pageList = roleManager.getPageInfo(vo);
		Map<String, Object> mapData = new HashMap<String, Object>();
		mapData.put("total", pageList.getCount());
		mapData.put("rows", pageList.getPageObjects());
		return mapData;
	}

	/**
	 * 功能说明：跳转到新增页面
	 */
	@Token(save = true)
	@RequestMapping(value = "add.action", method = RequestMethod.GET)
	public ModelAndView add(HttpServletRequest request) {
		ModelAndView view = new ModelAndView(EDIT);
		Role role = new Role();
		if (Validator.isNotNull(request.getParameter("roleId"))) {
			ParamsVo<Role> vo = new ParamsVo<Role>();
			vo.setInfoId(request.getParameter("roleId"));
			role = (Role) getBaseManager().getInfoById(vo);
		}
		String plguinSwitch = Validator.getDefaultStr(SystemTools.getInstance().getValue("org_act_switch"), "0");
		view.addObject("pluginsSwitch", plguinSwitch);
		view.addObject("orgId", request.getParameter("orgId"));
		String orgParam = request.getParameter("orgParam");
		if (Validator.isNotNull(orgParam)) {
			view.addObject("orgParam", orgParam);
		}
		view.addObject("item", role);
		return view;
	}

	/**
	 * TODO 保存角色信息.  
	 */
	@Token(remove = true)
	@RequestMapping(value = "/save.action", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg save(HttpServletRequest request, HttpServletResponse response, @ModelAttribute Role item) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");
		ParamsVo<Role> vo = getParamsVo(request);
		long times = DateUtils.toLong(new Date());
		User user = this.getSessionUser(request);
		if (Validator.isNotNull(item.getRoleId())) {//对角色信息修改
			item.setUpdateTime(times);
			item.setUpdateUser(user.getUserEname());
			if (Validator.isNull(item.getDelStatus()) && Validator.isNotNull(request.getParameter("orgId"))) {
				item.setDelStatus(request.getParameter("orgId"));
				ParamsVo<Org> oVo = new ParamsVo<Org>();
				oVo.setInfoId(item.getDelStatus());
				Org org = (Org) orgManager.getInfoById(oVo);
				item.setRoleRemark(org.getFullCname());
			}
			vo.setObj(item);
			boolean mark = getBaseManager().editInfo(vo);
			if (!mark) {
				rmsg = getResultMsg(request, "角色信息修改失败！");
			}
		} else {//添加角色信息
			item.setCreateUser(user.getUserEname());
			item.setSysEname("uct");
			String orgParam = request.getParameter("orgParam");
			if (Validator.isNotNull(orgParam)) {
				item.setDelStatus(orgParam);
			}
			if ("1".equals(SystemTools.getInstance().getValue("org_act_switch"))) {
				if (Validator.isNotNull(request.getParameter("orgId"))) {
					item.setDelStatus(request.getParameter("orgId"));
				}
			}
			item.setUpdateCount(0);
			item.setCreateTime(times);
			item.setRoleStatus(1);
			item.setCreateUser(user.getUserEname());
			if (Validator.isNotNull(item.getDelStatus())) {
				ParamsVo<Org> oVo = new ParamsVo<Org>();
				oVo.setInfoId(item.getDelStatus());
				Org org = (Org) orgManager.getInfoById(oVo);
				item.setRoleRemark(org.getFullCname());
			}
			vo.setObj(item);
			vo.setKey("checkRoleEname");
			String flag = String.valueOf(roleManager.execute(vo));
			if ("true".equals(flag)) {
				vo.setParams("orgId", item.getDelStatus());
				vo.setParams("synchSub", request.getParameter("synchSub"));
				String id = getBaseManager().saveInfo(vo);
				if (Validator.isNull(id)) {
					rmsg = getResultMsg(request, "角色信息添加失败！");
				}
			} else {
				rmsg = getResultMsg(request, "角色标识已存在,操作失败！");
			}
		}
		return rmsg;
	}

	//删除机构信息
	@RequestMapping("del.action")
	@ResponseBody
	public ResultMsg delete(HttpServletRequest request, String id) {
		ResultMsg rmsg = new ResultMsg("T", "删除成功！");
		ParamsVo<Role> vo = getParamsVo(request);
		if (isNotNull(id)) {
			vo.setInfoId(id);
			vo.setKey("deleteOrg");
			vo.setParams("infoType", "role");
			String msg = String.valueOf(uctProxyManager.doInvoke(vo));
			if (Validator.isNotNull(msg)) {
				rmsg.setFlag("F");
				rmsg.setMsg(msg);
			}
		} else {
			rmsg.setFlag("H");
			rmsg.setMsg("请选择要删除的角色！");
		}
		return rmsg;
	}

	/**
	 * 功能说明：跳转到角色授权页面
	 */
	@RequestMapping("role-act.action")
	public ModelAndView roleAct(HttpServletRequest request, String roleId) {
		ModelAndView view = new ModelAndView(getPrefix() + "act");
		view.addObject("roleId", roleId);
		return view;
	}

	/**
	 * 获取权限分配列表
	 */
	@RequestMapping("role-act!data.action")
	@ResponseBody
	public Object dataActs(HttpServletRequest request, String roleId, String id) throws Exception {
		id = Validator.getDefaultStr(id, "0");
		Act actVo = new Act();
		actVo.setFatherId(id);
		ParamsVo<Act> vo = new ParamsVo<Act>();
		vo.setObj(actVo);
		User user = this.getSessionUser(request);
		if (!Validator.isEmpty(user)) {
			vo.setParams("userOrgId", user.getOrgId());
			vo.setParams("sysUser", getSysFlag(request));//是否为系统用户
		}
		vo.setKey("findActForOrg");
		List<Act> actList = (List<Act>) uctProxyManager.doInvoke(vo);
		ParamsVo<ActGive> agVo = new ParamsVo<ActGive>();
		agVo.setParams("roleId", roleId);
		agVo.setParams("giveType", "role");
		agVo.setKey("GiveListByOrgId");
		List<ActGive> giveList = (List<ActGive>) actGiveManager.execute(agVo);

		JSONArray jary = new JSONArray();
		for (int i = 0; i < actList.size(); i++) {
			Act act = actList.get(i);
			JSONObject jvo = JSONObject.fromObject(act);
			if (act.getSubCount() != null && act.getSubCount() > 0) {
				jvo.put("state", "closed");
			} else {
				jvo.put("state", "opened");
			}
			String hasGive = hasGive(giveList, act.getActId()) ? "T" : "F";
			jvo.put("hasGive", hasGive);
			jary.add(jvo);
		}
		return jary;
	}

	protected BaseManager<Role> getBaseManager() {
		return roleManager;
	}

	protected String getPrefix() {
		return "uct/role-";
	}

	/**
	 * 判断是否包含该权限值
	 * @param giveList 分配的权限值
	 * @param actId 权限值id
	 * @return boolean
	 */
	private boolean hasGive(List<ActGive> giveList, String actId) {
		for (int j = 0; j < giveList.size(); j++) {
			ActGive give = giveList.get(j);
			if (actId.equals(give.getActId())) {
				return true;
			}
		}
		return false;
	}

}
